package com.hqyj.service.impl;

import com.hqyj.dao.PaperQuestionRelMapper;
import com.hqyj.pojo.Paper;
import com.hqyj.dao.PaperMapper;
import com.hqyj.pojo.PaperQuestionRel;
import com.hqyj.service.IPaperQuestionRelService;
import com.hqyj.service.IPaperService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.service.IQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rock
 * @since 2023-10-09
 */
@Service
@Slf4j
public class PaperServiceImpl extends ServiceImpl<PaperMapper, Paper> implements IPaperService {

    @Resource
    PaperMapper paperMapper;
    @Resource
    IPaperQuestionRelService iPaperQuestionRelService;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Autowired
    IQuestionService questionService;
    @Override
    @Transactional
    public HashMap<String, Object> randomPaper(Paper paper) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        //查询题库id，存入redis缓存中
        questionService.queryQuId();
        //插入试卷
        int num = paperMapper.insert(paper);
        if(num>0){
            //随机获取题库id
            Set<Object> set = redisTemplate.opsForSet().distinctRandomMembers("paper:random",10);
            //把set转换成list
            List<Object> listId = set.stream().collect(Collectors.toList());
            //批量插入中间表
            List<PaperQuestionRel> list = new LinkedList<>();
            for(int i=0;i<10;i++){
                PaperQuestionRel pq = new PaperQuestionRel();
                pq.setPaperId(paper.getPaperId());
                pq.setQuestionId(Integer.parseInt(listId.get(i)+""));
                list.add(pq);
            }
            //批量插入
            boolean is = iPaperQuestionRelService.saveBatch(list);
            if(is){
                log.info("试卷生成成功");
                map.put("code",200);
                map.put("msg","试卷生成成功");
                return map;
            }

        }
        log.info("试卷生成失败");
        map.put("code",500);
        map.put("msg","试卷生成失败");
        return map;
    }
}
